﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Helper.FullTextIndex;

namespace TI.TI_DruginfoAnalizer
{
   public class TextAnalizer
   {
       //хранилище эталонов 
       private string dictionaryStorePath { get; set; }
       private string idFieldName { get; set; }
       private string infoFieldName { get; set; }
       private Engine index =null;

       public class TextItem : IFullindexObject {
           private string _ID = Guid.NewGuid().ToString();
           public string ID
           {
               get { return _ID; }
           }

           public string ValueInfo
           {
               get;
               set;
           }


           public int LengthRank { get { return Terms.Count; } }

           /// <summary>
           /// значение в виде уникальных термов
           /// </summary>
           public List<string> Terms { get { return RamEngine.ParseText(ValueInfo); } }
       }

       public TextAnalizer(string _dictionaryStorePath,                          
                            string _infoFieldName,
                            string _idFieldName) {

                                dictionaryStorePath = _dictionaryStorePath;
                                idFieldName = _idFieldName;
                                infoFieldName = _infoFieldName;
                                index = new Engine (dictionaryStorePath);
       }

       /// <summary>
       /// Сравнивает текст с эталонами.
       /// Возвращает ид эталона если все слова эталона присутсвуют в выражении поиска совпадают с textValue
       /// </summary>
       /// <param name="textValue"></param>
       /// <returns></returns>
       public string Compare(string textValue) {           
           textValue = ClearForbiidenChar(textValue);
           List<Engine.SearchResult> applicants = index.SearchByField(infoFieldName, idFieldName, textValue);
           
           //кандидаты отсутствуют 
           if (applicants.Count == 0)   
                        return string.Empty;
           List<IFullindexObject> arr = new List<IFullindexObject>();
           foreach (IFullindexObject i in applicants) {
               arr.Add((IFullindexObject)i);
           }

           //выбрать в кандидатах
           var v=FindInApplicants (arr, textValue, "~0.7f");

           return (v==null?string.Empty:v.ValueInfo);
       }
      
       private string ClearForbiidenChar(string value) {

           value = value.Replace("+", "");
           value = value.Replace("*", "");
           value = value.Replace("[", "");
           value = value.Replace("]", "");
           value = value.Replace("^", "");
           value = value.Replace("$", "");
           value = value.Replace("-", "");
           value = value.Replace(".", "");
           value = value.Replace("(", "");
           value = value.Replace(")", "");
           value = value.Replace(":", "");
           return value;
       }

       /// <summary>
       /// Поиск в претендентах 
       /// </summary>
       /// <param name="applicants"></param>
       /// <param name="value"></param>
       /// <param name="accuracy"></param>
       /// <returns></returns>
       private IFullindexObject  FindInApplicants(List<IFullindexObject> applicants, string value, string accuracy)
       {
           value = ClearForbiidenChar(value);
           List<DictionaryApplicant> resut = new List<DictionaryApplicant>();

           //формируем индекс из поисковой строки 
           Helper.FullTextIndex.RamEngine engine = new RamEngine();
           List<IFullindexObject> textList = new List<IFullindexObject>();
           textList.Add(new TextItem() { ValueInfo = value });
           engine.IndexCollection(textList);

           List<IFullindexObject> result= new List<IFullindexObject> ();
           foreach (IFullindexObject i in applicants)
           {
               result =  engine.SearchByField("ValueInfo", "ID", ClearForbiidenChar(i.ValueInfo) + accuracy).ToList<IFullindexObject>() ;
               if (null == result) 
                         return null;

               if (result.Count == 1)
                        return result[0]; 

           }

           return null;

       }

   }

   public class DictionaryApplicant : Engine.SearchResult
   {
       public int RatingValue { get; set; }
   }
}
